import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/course/course_detail/app_bar/course_detail_app_bar.dart';
import 'package:edu/pages/course/course_detail/bottom_bar/course_detail_bottom_bar.dart';
import 'package:edu/pages/course/course_detail/header/course_detail_header.dart';
import 'package:edu/pages/course/course_detail/course_detail_page_logic.dart';
import 'package:edu/pages/course/course_detail/summary/course_detail_summary.dart';
import 'package:edu/pages/course/course_detail/tab/course_detail_tab.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class CourseDetailPage extends StatefulWidget {
  const CourseDetailPage({super.key});

  @override
  State<CourseDetailPage> createState() => _CourseDetailPageState();
}

class _CourseDetailPageState extends State<CourseDetailPage>
    with TickerProviderStateMixin {
  late final GlobalKey _appBarShoppingCartButtonKey = GlobalKey();
  late final GlobalKey _bottomPurchaseButtonKey = GlobalKey();

  late OverlayEntry _animatedOverlayEntry;
  late AnimationController _animationController;
  late Animation<Offset> _animation;

  @override
  void initState() {
    super.initState();
    context.read<CourseDetailPageLogic>().init();

    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _animatedOverlayEntry.remove();
        _animationController.reset();
      }
    });
  }

  void _startAnimation() {
    _animatedOverlayEntry = _createOverlayEntry();
    Overlay.of(context).insert(_animatedOverlayEntry);
    _animationController.forward();
  }

  OverlayEntry _createOverlayEntry() {
    final renderBox1 =
        _bottomPurchaseButtonKey.currentContext?.findRenderObject()
            as RenderBox;
    final startSize = renderBox1.size;
    final startOffset = renderBox1.localToGlobal(
      Offset(startSize.width * 0.5 - 8, startSize.height * 0.5 - 8),
    );

    final renderBox2 =
        _appBarShoppingCartButtonKey.currentContext?.findRenderObject()
            as RenderBox;
    final endSize = renderBox2.size;
    final endOffset = renderBox2.localToGlobal(
      Offset(endSize.width * 0.5 - 8, endSize.height * 0.5 - 8),
    );
    final tween = Tween<Offset>(begin: startOffset, end: endOffset);
    _animation = tween.animate(_animationController);

    return OverlayEntry(
      builder: (context) {
        return AnimatedBuilder(
          animation: _animation,
          builder: (context, child) {
            return Positioned(
              left: _animation.value.dx,
              top: _animation.value.dy,
              child: _buildMoving(),
            );
          },
        );
      },
    );
  }

  Widget _buildMoving() {
    return Container(
      padding: const EdgeInsets.all(1),
      width: 16,
      height: 16,
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: BorderRadius.circular(8),
      ),
      child: const Center(
        child: Text(
          '1',
          style: TextStyle(color: Colors.white, fontSize: 11),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CourseDetailAppBar(
        shoppingCartButtonKey: _appBarShoppingCartButtonKey,
      ),
      body: _buildMainBody(context),
      bottomNavigationBar: CourseDetailBottomBar(
        purchaseButtonKey: _bottomPurchaseButtonKey,
        startAnimate: _startAnimation,
      ),
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Selector<CourseDetailPageLogic, bool>(
      selector: (context, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return Selector<CourseDetailPageLogic, Tuple2<bool, bool>>(
            selector: (context, logic) =>
                Tuple2(logic.isLoading, logic.isError),
            builder: (context, value, child) {
              return EmptyContentWidget(
                isLoading: value.item1,
                isError: value.item2,
                reloadAction: () {
                  context.read<CourseDetailPageLogic>().loadCourseDetail();
                },
              );
            },
          );
        } else {
          return _buildContentBody(context);
        }
      },
    );
  }

  Widget _buildContentBody(BuildContext context) {
    return ScrollConfiguration(
      // 去掉滚动条
      behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
      child: NestedScrollView(
        scrollDirection: Axis.vertical,
        controller: context.read<CourseDetailPageLogic>().mainScrollController,
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return const [
            SliverToBoxAdapter(child: CourseDetailHeader()),
            SliverToBoxAdapter(child: CourseDetailSummary()),
          ];
        },
        body: const CourseDetailTab(),
      ),
    );
  }
}
